<template>
  <div>
    <fullscreenModal
      :modal="showModal"
      label="确认订单"
      :isShowEdit="false"
      :showSave="false"
      editType="other"
      @handleClose="handleClose()"
    >
      <van-cell class="boxs" icon="location-o" @click="handleEdit">
        <template>
          <div>
            <span>收货人：{{ siteData.receiver }}</span
            ><span style="float: right; margin-right: 20px">{{
              siteData.receiverContact
            }}</span>
          </div>
          <div style="display: flex; align-items: center">
            收货地址：<span class="addrs">{{
              siteData.provName +
              siteData.cityName +
              siteData.countyName +
              siteData.detailAddr
            }}</span>
            <van-icon name="arrow" class="right" />
          </div>
        </template>
      </van-cell>
      <div class="cenber">
        <div class="cartBox">
          <div v-for="(item, i) in oderList" :key="i">
            <van-cell
              :title="item.networkName"
              :value="item.payMethodLabel"
              icon="shop-o"
            />
            <div v-for="(val, index) in item.newArr" :key="index">
              <van-card
                :num="val.addAmount"
                :price="val.addSellingPrice.toFixed(2)"
                :desc="val.attrNames"
                :title="val.goodsName"
                :thumb="val.imgUrl"
              />
            </div>
            <div class="spanBox" @click="handleDelivery(item)">
              <p>配送方式</p>
              <p style="text-align: right">{{ item.deliveryLabel }}</p>
              <van-icon name="arrow" style="padding-top: 4px" />
            </div>
            <div class="spanBox">
              <p>运费</p>
              <p style="text-align: right">￥{{ item.carriage }}</p>
            </div>
            <div class="spanBox">
              <p class="spanTxt">
                {{ item.total }}件商品&nbsp;&nbsp;&nbsp;&nbsp;共计￥<span
                  style="color: #ee0a24; font-size: 16px"
                  >{{ item.subtotal }}</span
                >
              </p>
            </div>
            <van-field
              style="
                border-top: 1px solid #efefef;
                border-bottom: 1px solid #efefef;
              "
              v-model="item.remark"
              maxlength="100"
              label="订单备注"
              placeholder="选填(输入长度为100字以内)"
            />
          </div>
        </div>
        <van-submit-bar
          :price="Aomprice * 100"
          button-text="提交订单"
          @submit="handleSubmit"
        >
          <div class="yunfei" style="font-size: 13px">
            <p>在线扣款：{{ onlinePay.toFixed(2) }}</p>
            <p>线下刷卡：{{ offlinePay.toFixed(2) }}</p>
          </div>
        </van-submit-bar>
      </div>

      <div class="result" v-if="showResult">
        <div class="close" @click="handleAllClose()">
          <van-icon name="cross" size="20" />
        </div>
        <div v-if="isSuccess" class="isSuccess">
          <van-icon size="100" name="checked" />
          <p
            v-if="!showTxt"
            style="display: flex; flex-direction: column; line-height: 35px"
          >
            提交成功，请尽快付款
            <span>（ 页面 {{ closeTime }} 秒后将自动关闭 ）</span>
          </p>
          <p v-else>
            购买成功<span>（ 页面 {{ closeTime }} 秒后将自动关闭 ）</span>
          </p>
          <div>
            <a @click="jumpMyOrder()">去我的订单 >></a>
          </div>
        </div>
        <div v-else class="isFail">
          <van-icon size="100" name="clear" />
          <p>
            购买失败<span>（ 页面 {{ closeTime }} 秒后将自动关闭 ）</span>
          </p>
          <div>
            <a @click="jumpMyOrder()">去我的订单 >></a>
          </div>
          <ul
            class="msg"
            v-if="failMsg.config || failMsg.settlement || failMsg.payFail"
          >
            <li v-if="failMsg.config">
              <label>网点未配置：</label>
              <span>{{ failMsg.config }}</span>
            </li>
            <li v-if="failMsg.settlement">
              <label>支付中心未配置：</label>
              <span>{{ failMsg.settlement }}</span>
            </li>
            <li v-if="failMsg.payFail">
              <label>支付失败：</label>
              <span v-html="failMsg.payFail"></span>
            </li>
          </ul>
        </div>
      </div>
    </fullscreenModal>
    <full-loading v-if="loading"></full-loading>
    <van-action-sheet
      v-model="showDelivery"
      cancel-text="取消"
      :actions="deliveryDate"
      @select="onIsSelfConfirm"
    />
    <!-- 新增/详情/编辑 弹出框 -->

    <fullscreenModal
      :modal="addressModal"
      label="收货地址"
      :isShowEdit="false"
      :showSave="false"
      editType="other"
      @handleClose="addressModal = false"
    >
      <editForm ref="editFormRef" @refresh="handleRefresh"></editForm>
    </fullscreenModal>
    <payment
      ref="payment"
      @paySuccess="paySuccess"
      :money="payMoney"
      @payCancel="handleClose()"
    ></payment>
  </div>
</template>

<script>
import { getQuery } from "@api/platframe/mainFrame/address";
import { queryDealer } from "@/api/srvAssurance/shoppingMall/markeApi";
import {
  queryFreight,
  submitOrder,
  payOrder,
  batchOrder,
} from "@/api/srvAssurance/shoppingMall/order";
import editForm from "./address";
import payment from "@/components/confirmOrder";
export default {
  components: { editForm, payment },
  data() {
    return {
      loading: false,
      showModal: false,
      showTxt: false,
      showDelivery: false,
      showResult: false,
      isSuccess: true,
      addressModal: false,

      oderList: [],
      deliveryMode: "",
      deliveryLabel: "",
      deliveryDate: [],
      remark: "",
      total: 0,
      subtotal: 0,
      stateType: "",
      dataInfo: "",

      siteData: "",
      offlinePay: 0,
      onlinePay: 0,
      closeTime: 10,
      failMsg: {
        config: "",
        settlement: "",
        payFail: "",
      },
      payMoney: "",
      orderAmount: "",
      onlinePayOrderNos: [],
    };
  },
  computed: {
    // 计算总价
    Aomprice() {
      let price = 0;
      price += Number(this.subtotal);
      return price.toFixed(2);
    },
  },
  methods: {
    openMyCar(list, type) {
      this.showModal = true;
      this.loading = true;
      this.stateType = type;

      let arr = [];
      list.forEach((item, i) => {
        arr.push(item.networkId);
      });

      queryDealer(arr).then((res) => {
        if (res.code === 1000 && res.data) {
          list.forEach((item, i) => {
            let div = res.data[arr[i]];

            if (div.deliveryModeLabels.length == "2") {
              item.deliveryMode = "1";
              item.deliveryLabel = "快递";
              this.deliveryDate = [
                { value: 1, name: "快递" },
                { value: 2, name: "自提" },
              ];
            } else {
              if (div.deliveryModeLabels[0] == "快递") {
                item.deliveryMode = "1";
                item.deliveryLabel = "快递";
              } else {
                item.deliveryMode = "2";
                item.deliveryLabel = "自提";
              }
            }

            item.payMethod = div.payMethod;
            item.payMethodLabel = div.payMethodLabel;
          });
        }
      });

      this.oderList = list;
      this.getQueryData();
      setTimeout(() => {
        this.handleMode();
      }, 400);
      setTimeout(() => {
        this.loading = false;
      }, 700);
    },

    handleEdit() {
      this.addressModal = true;
    },
    handleDelivery(item) {
      this.showDelivery = true;
      this.dataInfo = item;
    },
    // 查询收货地址
    getQueryData() {
      let obj = { staffId: sessionStorage.getItem("userid") };
      getQuery(obj).then((res) => {
        if (res && res.code === 1000 && res.data) {
          res.data.forEach((item) => {
            if (item.isDefault == "1") {
              this.siteData = item;
            }
          });
        }
      });
    },
    handleRefresh(item) {
      this.siteData = item;
      this.addressModal = false;
      this.handleMode();
    },
    handleMode() {
      let data = {
        areaCode: this.siteData.countyCode,
        goodsShippingCalcs: [],
      };
      this.oderList.forEach((item) => {
        item.goodsTotal = 0;
        item.networkPrice = 0;
        item.total = 0;
        this.subtotal = 0;
        item.newArr.forEach((val) => {
          item.total += val.addAmount;
          item.networkPrice += val.addSellingPrice * val.addAmount;
          data.goodsShippingCalcs.push({
            count: val.addAmount,
            specDetailId: val.specDetailId,
            goodsId: val.goods_id || val.goodsId,
          });
        });
        queryFreight(data).then((res) => {
          if (res.code === 1000) {
            item.carriage = res.data;
            item.subtotal = item.networkPrice.toFixed(2);
            item.soldAmount = item.networkPrice + res.data;
            this.subtotal += item.soldAmount;
          }
        });
      });

      this.onlinePay = 0;
      this.offlinePay = 0;

      setTimeout(() => {
        this.oderList.forEach((item, i) => {
          if (item.payMethod == "2") {
            this.onlinePay += item.networkPrice + item.carriage;
          } else {
            this.offlinePay += item.networkPrice + item.carriage;
          }
        });
      }, 550);
    },
    onIsSelfConfirm(item) {
      this.dataInfo.deliveryMode = item.value;
      this.dataInfo.deliveryLabel = item.name;
      this.showDelivery = false;

      this.onlinePay = 0;
      this.offlinePay = 0;

      let val = this.dataInfo;
      if (item.value == 2) {
        this.subtotal = this.subtotal - val.carriage;
        val.carriage = 0;
      } else {
        val.carriage = val.soldAmount - val.networkPrice;
        this.subtotal = this.subtotal + val.carriage;
      }

      this.oderList.forEach((item, i) => {
        if (item.payMethod == "2") {
          this.onlinePay += item.networkPrice + item.carriage;
        } else {
          this.offlinePay += item.networkPrice + item.carriage;
        }
      });
    },
    handleSubmit() {
      let arr = [];
      this.oderList.forEach((item) => {
        item.newArr.forEach((val) => {
          val.specDetailId = val.specDetailId;
          val.goodsId = val.goods_id || val.goodsId;
          val.buyCount = val.addAmount;
        });
        arr.push({
          networkId: item.networkId,
          orderGoodss: item.newArr,
          deliveryMode: item.deliveryMode,
          remark: item.remark || "",
        });
      });

      let data = {};

      if (this.stateType) {
        data = {
          addrId: this.siteData.addrId,
          orderNetworks: arr,
        };
      } else {
        data = {
          addrId: this.siteData.addrId,
          orderNetworks: arr,
        };
      }
      submitOrder(data).then((res) => {
        if (res.code === 1000) {
          // 线上支付
          if (
            res.data.offlinePaymentAmount == 0 &&
            res.data.onlinePaymentAmount != 0
          ) {
            this.showTxt = true;
            this.payMoney = res.data.onlinePaymentAmount + "";
            this.orderAmount = res.data.onlinePaymentAmount;
            this.onlinePayOrderNos = res.data.onlinePayOrderNos;
            this.$refs.payment.isProof();
          }

          // 线下支付
          if (
            res.data.onlinePaymentAmount == 0 &&
            res.data.offlinePaymentAmount != 0
          ) {
            this.showTxt = false;
            this.showResultFun(true);
          }

          // 多种支付
          if (
            res.data.onlinePaymentAmount != 0 &&
            res.data.offlinePaymentAmount != 0
          ) {
            this.showTxt = true;
            this.payMoney = res.data.onlinePaymentAmount + "";
            this.orderAmount = res.data.onlinePaymentAmount;
            this.onlinePayOrderNos = res.data.onlinePayOrderNos;
            this.$refs.payment.isProof();
          }
        }
      });
    },
    // 去我的订单页面
    jumpMyOrder() {
      this.$router.push({ name: "eshop-goodsOrder" });
    },
    paySuccess() {
      if (this.onlinePayOrderNos.length > 1) {
        let dataList = {
          paymentAmount: this.orderAmount,
          orderNos: this.onlinePayOrderNos,
        };
        batchOrder(dataList).then((res) => {
          if (res.code == 1000) {
            if (res.data) {
              this.$Notify({ type: "success", message: "支付成功！" });
              this.handleAllClose();
            } else {
              this.handleClose();
            }
          }
        });
      } else {
        let dataList = {
          orderAmount: this.orderAmount,
          orderNo: this.onlinePayOrderNos.toString(),
        };
        payOrder(dataList).then((res) => {
          if (res.code == 1000) {
            if (res.data) {
              this.$Notify({ type: "success", message: "支付成功！" });
              this.handleAllClose();
            } else {
              this.handleClose();
            }
          }
        });
      }
    },
    showResultFun(flag) {
      this.closeTime = 10;
      this.showResult = true;
      this.isSuccess = flag;
      let timer = setInterval(() => {
        this.closeTime--;
        if (this.closeTime <= 0 || !this.showResult) {
          clearInterval(timer);
          if (this.showResult) {
            if (this.isSuccess) {
              // 订单成功，关闭购物车
              this.handleAllClose();
            } else {
              // 订单失败，返回购物车
              this.handleClose();
            }
          }
        }
      }, 1000);
    },
    handleAllClose() {
      this.showResult = false;
      this.showModal = false;
      this.$emit("refresh");
    },
    // 关闭结果
    handleClose() {
      this.showResult = false;
      this.showModal = false;
      this.$emit("refresh");
    },
    resetForm() {
      this.loading = false;
      this.showModal = false;
      this.showDelivery = false;
      this.showResult = false;
      this.addressModal = false;
      this.isSuccess = false;
      this.showTxt = false;

      this.oderList = [];
      this.deliveryMode = "";
      this.deliveryLabel = "";
      this.deliveryDate = [];
      this.remark = "";
      this.total = 0;
      this.subtotal = 0;
      this.siteData = "";
      this.offlinePay = 0;
      this.onlinePay = 0;
      this.stateType = "";
      this.payMoney = "";
      this.orderAmount = "";

      this.payMoney = "";
      this.orderAmount = "";
      this.onlinePayOrderNos = [];
      this.failMsg = {
        config: "",
        settlement: "",
        payFail: "",
      };
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .van-card:not(:first-child) {
  margin-top: 0;
}

/deep/ .van-cell__left-icon {
  font-size: 25px;
}
/deep/ .van-card__price {
  color: #ee0a24;
}
/deep/ .van-card__num {
  color: #000;
}
.boxs {
  height: 80px;
  color: #787878;
  display: flex;
  align-items: center;
}

.addrs {
  position: relative;
  display: inline-block;
  width: 230px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.right {
  position: absolute;
  right: -8px;
  top: 12px;
  font-size: 26px;
  color: #787878;
}
.cenber {
  background: #ededed;
}
.cartBox {
  padding-top: 10px;
}
.spanBox {
  display: flex;

  border-top: 1px solid #efefef;
  color: #323233;
  padding: 10px 16px;
  background: #fff;
  p {
    flex: 1;
  }
  .spanTxt {
    text-align: right;
  }
}

.cartBox /deep/ .van-card__title {
  font-size: 14px;
}
.cartBox /deep/ .van-card__desc {
  line-height: 0.7rem;
}

.result {
  position: fixed;
  background: #fff;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  text-align: center;
  z-index: 999;
  padding-top: 120px;
  p {
    line-height: 80px;
    font-size: 16px;
    font-weight: bold;
    span {
      font-size: 13px;
      color: #aaa;
    }
  }
  .close {
    position: absolute;
    right: 15px;
    top: 15px;
    cursor: pointer;
  }
  .isFail {
    color: #ed4014;
  }
  .isSuccess {
    color: #19be6b;
  }
  a {
    font-size: 13px;
    margin: 0 40px;
  }
  ul {
    width: 95%;
    margin: 20px auto;
    font-size: 12px;
    li {
      line-height: 25px;
      text-align: center;
      label {
        margin-right: 8px;
      }
      span {
        color: #333;
      }
    }
  }
}
</style>
